#include "GetFriendListTask.h"
#include "TcpConnection.h"
#include "MessageCodec.h"
#include "protocol.h"
#include "block_log.h"
#include "ConnectPool.h"
#include <optional>
#include <thread>
#include <memory>

GetFriendListTask::GetFriendListTask(TcpConnection* conn, const std::string& jsonBody)
    : m_conn(conn), m_jsonBody(jsonBody)
{
}

GetFriendListTask::~GetFriendListTask()
{
}

void GetFriendListTask::work(void* arg)
{
    Debug("GetFriendListTask 开始执行");
    
    // 步骤 1: 解析获取好友列表请求
    auto requestOpt = MessageCodec::getFriendListRequestFromJson(m_jsonBody);
    if (!requestOpt) {
        Debug("获取好友列表请求 JSON 解析失败");
        
        // 发送错误响应
        GetFriendListResponse errorRes;
        errorRes.success = false;
        errorRes.message = "请求格式错误";
        
        auto responseData = MessageCodec::encode(errorRes);
        m_conn->sendResponseAsync(responseData);
        return;
    }
    
    GetFriendListRequest req = *requestOpt;
    Debug("处理获取好友列表请求 - 用户ID: %lu", req.user_id);
    
    // 步骤 2: 从连接池获取数据库连接
    auto connPool = ConnectionPool::getConnectionPool();
    auto dbConn = connPool->getConnection();
    
    if (!dbConn) {
        Debug("获取数据库连接失败");
        
        GetFriendListResponse errorRes;
        errorRes.success = false;
        errorRes.message = "服务器繁忙，请稍后重试";
        
        auto responseData = MessageCodec::encode(errorRes);
        m_conn->sendResponseAsync(responseData);
        return;
    }
    
    // 步骤 3: 查询数据库获取好友列表
    std::vector<FriendInfo> friends;
    bool success = false;
    std::string errorMsg = "获取好友列表失败";
    
    try {
        Connection* conn = dbConn->getConnection();
        
        // 查询好友列表：联合查询 friendships 和 users 表
        std::unique_ptr<PreparedStatement> pstmt(
            conn->prepareStatement(
                "SELECT u.user_id, u.username, u.nickname, u.avatar_url, u.status "
                "FROM friendships f "
                "JOIN users u ON f.friend_id = u.user_id "
                "WHERE f.user_id = ? AND f.status = 1"
            )
        );
        
        pstmt->setUInt64(1, req.user_id);
        
        std::unique_ptr<ResultSet> res(pstmt->executeQuery());
        
        while (res->next()) {
            FriendInfo friendInfo;
            friendInfo.user_id = res->getUInt64("user_id");
            friendInfo.username = res->getString("username");
            friendInfo.nickname = res->getString("nickname");
            friendInfo.avatar = res->getString("avatar_url");
            friendInfo.status = res->getInt("status");
            
            friends.push_back(friendInfo);
            
            Debug("好友 - ID: %lu, 账号: %s, 昵称: %s", 
                  friendInfo.user_id, 
                  friendInfo.username.c_str(), 
                  friendInfo.nickname.c_str());
        }
        
        success = true;
        errorMsg = friends.empty() ? "暂无好友" : "获取成功";
        
        Debug("用户 %lu 的好友列表查询成功，共 %zu 个好友", req.user_id, friends.size());
        
    } catch (const SQLException& e) {
        Debug("数据库查询异常: %s (错误码: %d)", e.what(), e.getErrorCode());
        errorMsg = "服务器内部错误";
        success = false;
    }
    
    // 步骤 4: 构造好友列表响应
    GetFriendListResponse response;
    response.success = success;
    response.message = errorMsg;
    response.friends = friends;
    
    Debug("好友列表响应 - 成功: %d, 消息: %s, 好友数: %zu", 
          response.success, 
          response.message.c_str(), 
          response.friends.size());
    
    // 步骤 5: 编码响应并异步发送
    auto responseData = MessageCodec::encode(response);
    m_conn->sendResponseAsync(responseData);
    
    Debug("GetFriendListTask 执行完成");
}

